<?php

namespace app\api\controller;


use addons\epay\library\Service;
use app\api\model\House as HouseM;
use app\api\model\Order;
use app\api\model\Third;
use app\common\controller\Api;
use Yansongda\Pay\Pay as Payse;
/**
 * 支付接口
 */
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function RechargeData()
    {
        $recharge=config('site.recharge');
        foreach ($recharge as $k=>$vo){
            $list[$k]['price']=$k;
            $list[$k]['number']=$vo;
        }
        $this->success('',array_values($list));
    }
    public function RechargeOredr()
    {
        $recharge=config('site.recharge');
        $param = request()->param();
        $user=$this->auth;
        $Order = new Order();
        $data['type']=2;
        $data['price']=$param['price'];
        $data['balance']=$recharge[$param['price']];
        $order_no=date('YmdHis').$user->id;
        $Order->user_id=$user->id;
        $Order->order_no=$order_no;
        $Order->money=$param['price'];
        $Order->data_json=json_encode($data, JSON_FORCE_OBJECT);
        $Order->save();
        $rData['order_id']=$Order->id;
        $this->success('',$rData);
    }

    public function pay(){
        $param = request()->param();
        $user=$this->auth;
        $Order = new Order();
        $Third = new Third();
        $order_find=$Order->get($param['order_id']);
        $where_third['user_id']=$user->id;
        $third_find=$Third->get($where_third);
        $notifyurl=request()->root(true).'/api/pay/notifyx/paytype/wechat';
        $returnurl=request()->root(true).'/api/pay/returnx/paytype/wechat';
        $params = [
            'type'         => "wechat",
            'orderid' => $order_find['order_no'],
            'title'        => "支付费用",
            'amount'       => $order_find['money'],
            'method'       => "mini",
            'openid'       => $third_find['openid'],
            'notifyurl'    => $notifyurl,
            'returnurl'    => $returnurl,
        ];
        $result = Service::submitOrder($params);
        $this->success('',$result);
    }
    /**
     * 支付成功回调
     */
    public function notifyx()
    {
        $type = $this->request->param('paytype');
        $pay = Service::checkNotify($type);
        $Order = new Order();
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
        try {
            $out_trade_no = $data['out_trade_no'];
            $where['order_no']=$out_trade_no;
            $order_find=$Order->get($where);
            if($order_find['pay_time']==0){
                $data_json=json_decode($order_find['data_json'], true);
                $this->user_money($order_find['user_id'],$data_json['balance'],1,"充值钢豆");
                $updata['pay_time']=time();
                $Order->save($updata,$where);
            }

        } catch (Exception $e) {
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }
}
